import router from "@/router";
import defaultSettings from "@/config/defaultSettings";
import ProcessHelper from "@/config/ProcessHelper";
import { GetOperatorMenuList } from "@/api/index";

/* 主路由 */
const Main = resolve =>
  require.ensure([], () => resolve(require("@/views/Main/Main")), "Main");
/* 空页面 */
const Blank = resolve =>
  require.ensure([], () => resolve(require("@/views/Main/Blank")), "Blank");

var uuid = require("node-uuid");

let inited = false;
let addRouter = [];
let addRouterExpand = [];

const rootUrl = () => {
  if (ProcessHelper.isProduction() || ProcessHelper.isPreview()) {
    return defaultSettings.publishRootUrl;
  } else {
    return defaultSettings.localRootUrl;
  }
};

export const getAddRouter = () => {
  return addRouter;
};

export const getAddRouterExpand = () => {
  return addRouterExpand;
};

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: "*",
  redirect: "/404",
  hidden: true
};

const userRouter = [
  //home
  {
    title: "首页",
    icon: "home",
    children: [
      {
        path: "/Home/Introduce",
        title: "框架介绍",
        icon: "container"
      }
      // {
      //   path: "/Home/Statis",
      //   title: "运营统计"
      // }
    ]
  },
  // account
  {
    title: "个人页",
    icon: "user",
    children: [
      // {
      //   path: "/account/center/Index",
      //   title: "个人中心"
      // },
      {
        path: "/account/settings/Index",
        title: "个人设置",
        icon: "user"
      }
    ]
  }
];

// 开发模式额外路由
const devRouter = [
  {
    title: "开发",
    icon: "code",
    children: [
      {
        path: "/Base_Manage/Base_DbLink/List",
        title: "数据库连接",
        icon: "database"
      },
      {
        path: "/Base_Manage/BuildCode/List",
        title: "代码生成",
        icon: "code"
      },
      {
        path: "/Develop/Icon",
        title: "Icon图标",
        icon: "smile"
      },
      {
        path: "/Develop/Button",
        title: "按钮",
        icon: "play-square"
      },
      {
        path: "/Develop/Vanform",
        title: "表单",
        icon: "profile"
      },
      {
        path: "/Develop/Table",
        title: "表格",
        icon: "table"
      },
      {
        path: "/Develop/User",
        title: "会员中心",
        icon: "home"
      },
      {
        path: "/Develop/Cart",
        title: "购物车",
        icon: "shopping-cart"
      },
      {
        path: "/Develop/Goods",
        title: "商品详情",
        icon: "tag"
      },
      {
        path: "/Develop/UploadImg",
        title: "图片上传Demo",
        icon: "picture"
      },
      {
        path: "/Develop/UploadFile",
        title: "文件上传Demo",
        icon: "file-image"
      },
      {
        path: "/Develop/Editor",
        title: "富文本Demo",
        icon: "file-text"
      },
      {
        path: "/OutHtml/swagger",
        title: "swagger",
        component: () => import(`@/components/OutHtml/Index`),
        pathUrl: rootUrl() + "/swagger/index.html",
        icon: "html5"
      },
      {
        path: "/OutHtml/baidu",
        title: "百度",
        component: () => import(`@/components/OutHtml/Index`),
        pathUrl: "https://www.baidu.com",
        icon: "chrome"
      }
    ]
  }
];

export const initRouter = (to, from, next) => {
  return new Promise((res, rej) => {
    if (inited) {
      res();
    } else {
      generatorDynamicRouter().then(dynamicRouter => {
        //router.options.routes.push(dynamicRouter);
        router.addRoutes(dynamicRouter);

        inited = true;
        next({ ...to, replace: true });
      });
    }
  });
};

/**
 * 获取路由菜单信息
 *
 * 1. 调用 getRouterByUser() 访问后端接口获得路由结构数组
 *    @see https://github.com/sendya/ant-design-pro-vue/blob/feature/dynamic-menu/public/dynamic-menu.json
 * 2. 调用
 * @returns {Promise<any>}
 */
const generatorDynamicRouter = () => {
  return new Promise((resolve, reject) => {
    // ajax
    getRouterByUser()
      .then(res => {
        let allRouters = [];

        //首页根路由
        let mainRouter = {
          // 主路由
          path: "",
          name: "Main",
          component: Main,
          children: [
            {
              // 首页
              path: "",
              name: "Home",
              component: () => import(`@/views/Home/Home`),
              children: [
                {
                  path: "/Home",
                  component: Blank,
                  children: [
                    {
                      path: "/Home",
                      redirect: "/Home/HomeHot"
                    },
                    {
                      // 热卖
                      path: "HomeHot",
                      name: "HomeHot",
                      meta: { title: "介绍", requireAuth: true },
                      component: () => import(`@/views/Home/HomeHot`)
                    },
                    {
                      // 新品
                      path: "HomeNew",
                      name: "HomeNew",
                      meta: { title: "推荐", requireAuth: true },
                      component: () => import(`@/views/Home/HomeNew`)
                    },
                    {
                      // 优惠
                      path: "HomeTool",
                      name: "HomeTool",
                      meta: { title: "应用", requireAuth: true },
                      component: () => import(`@/views/Home/HomeTool`)
                    },
                    {
                      // 更多
                      path: "HomeMore",
                      name: "HomeMore",
                      meta: { title: "更多", requireAuth: true },
                      component: () => import(`@/views/Home/HomeMore`)
                    }
                  ]
                }
              ]
            },
            {
              // 分类
              path: "/Categories",
              component: Blank,
              children: [
                {
                  path: "Categories",
                  name: "Categories",
                  meta: { title: "分类", requireAuth: true },
                  component: () => import(`@/views/Categories/Categories`)
                }
              ]
            },
            {
              // 消息
              path: "/Notice",
              component: Blank,
              children: [
                {
                  path: "Index",
                  name: "Notice",
                  meta: { title: "消息", requireAuth: true },
                  component: () => import(`@/views/Notice/Notice`)
                }
              ]
            },
            {
              // 我的
              path: "/account",
              component: Blank,
              children: [
                {
                  path: "account",
                  name: "account",
                  meta: { title: "我的", requireAuth: true },
                  component: () => import(`@/views/account/Account`)
                }
              ]
            }
          ]
        };

        allRouters.push(mainRouter);

        if (!ProcessHelper.isProduction()) {
          res.push(...devRouter);
        }

        addRouter = generator(res);
        addRouterExpand = getChildrens(addRouter);

        allRouters.push(...addRouter);
        allRouters.push(notFoundRouter);

        resolve(allRouters);
      })
      .catch(err => {
        reject(err);
      });
  });
};

/**
 * 获取后端路由信息的 axios API
 * @returns {Promise}
 */
const getRouterByUser = () => {
  return new Promise((resolve, reject) => {
    GetOperatorMenuList().then(resJson => {
      if (resJson.Success) {
        resolve(resJson.Data);
      }
    });
  });
};

/**
 * 格式化 后端 结构信息并递归生成层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    let hasChildren = item.children && item.children.length > 0;
    let component = {};
    if (hasChildren) {
      component = Blank;
    } else if (item.path) {
      component = item.component || (() => import(`@/views${item.path}`));
    }
    let currentRouter = {
      // 路由名称，建议唯一
      name: uuid.v4(),
      // 该路由对应页面的 组件
      component: component,
      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: {
        title: item.title,
        icon: item.icon || undefined,
        pathUrl: item.pathUrl || undefined
      },
      text: item.title //vant 树型控件使用
    };

    //有子菜单
    if (hasChildren) {
      currentRouter.path = `/${uuid.v4()}`;
    } else if (item.path) {
      //页面
      currentRouter.path = item.path;
      currentRouter.path = currentRouter.path.replace("//", "/");
      currentRouter.name = currentRouter.path;
    }

    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect);
    // 是否有子菜单，并递归处理
    if (hasChildren) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter);
    }
    return currentRouter;
  });
};

const getChildrens = allNodes => {
  var childrens = [];
  if (allNodes != undefined && allNodes.length > 0) {
    childrens.push(...allNodes.filter(item => item.children == undefined));
    allNodes.forEach(item => {
      childrens.push(...getChildrens(item.children));
    });
  }
  return childrens;
};
